// 消息模块-mysql服务处理

// 引入数据库模块
const db = require('../config/mysql.js')
const utils = require("../common/utils")


// 获取好友招呼语
const getHelloFromFriend = (uid, fid) => {
  return new Promise((resolve, reject) => {
    let sql = `select message, message_type, know_time from fmessage, friend where friend.user_id = "${uid}" and friend.friend_id = "${fid}" and message_type = 4`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.length == 1) {
        result[0].know_time = utils.formatDate(new Date(result[0].know_time).getTime())
        db.query(`update fmessage set send_time = "${result[0].know_time}" where user_id = "${fid}" and friend_id = "${uid}" and message_type = 4`, (err1, result1) => {
          if (err1) return reject(err1)
          if (result1.affectedRows == 1) {
            result[0].send_time = result[0].know_time
            // delete result[0].user_id
            return resolve(result[0])
          }
        })
      } else {
        result[result.length - 1].know_time = utils.formatDate(new Date(result[result.length - 1].know_time).getTime())
        db.query(`update fmessage set send_time = "${result[result.length - 1].know_time}" where user_id = "${fid}" and friend_id = "${uid}" and message_type = 4`, (err1, result1) => {
          if (err1) return reject(err1)
          result[result.length - 1].send_time = result[result.length - 1].know_time
          return resolve(result[result.length - 1])
        })
      }
    })
  })
}

// 发送招呼消息
const helloFirend = (uid, fid, message, type) => {
  return new Promise((resolve, reject) => {
    let sql = `insert into fmessage (user_id, friend_id, message, message_type) values("${uid}", "${fid}", "${message}", 4)`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("发送成功")
      return reject('发送失败')
    })
  })
}

module.exports = {
 helloFirend,
 getHelloFromFriend
}